var express = require('express');
var router = express.Router();
var userHelper = require("../lib/userHelper.js");
var _ = require("underscore");
var errorMap = require(__dirname+"/../config/ErrorCode.js").ERRORMAP;
var sendAuto = require(__dirname+"/../lib/HttpHandler.js").sendAuto;
var Q = require("q");
//exports.init =init;
/* GET home page. */
router.get('/', function(req, res, next) {
    res.render('index', { title: "express" });
});

router.get("/send-invitation",function(req,res){
    var param = _.extend(req.query);
    console.log(param);
    if(_.isEmpty(param.mobile)){
        sendAuto(req,res,errorMap.paramError);
    }else{
        userHelper.checkMobileExist(param)
            .then(function(res){
                if(res === true){
                    return Q.reject(errorMap.mobileExist);
                }else{
                    return Q(param);
                }
            }).then(userHelper.sendInvitation)
            .then(function(result){
                console.log(result);
                sendAuto(req,res,{success:true,result:result});
            },function(err){
                console.log(err);
                _.defaults(err,{
                    success:false
                });
                sendAuto(req,res,err);
            });
    }
});

router.post("/sign-up",function(req,res){
    var param = _.extend(req.body);
    console.log(param);
    if(_.isEmpty(param.mobile) || _.isEmpty(param.invitationCode)||_.isEmpty(param.identifyCode)){
        sendAuto(req,res,errorMap.paramError);
    }else{
        userHelper.signUp(param)
            .then(function(result){
                sendAuto(req,res,{success:true,result:result});
            },function(err){
                _.defaults(err,{
                    success:false
                });
                sendAuto(req,res,err);
            });
    }
});
router.get("/sign-up-success",function(req,res){
    console.log("sign-up-success");
    res.render('signup_success', { title: "express" });
});

router.initParam = function(param){
    userHelper.init(param);
};
module.exports = router;
